package com.ellecity06.cwhiskymall.ui.mine

import android.annotation.SuppressLint
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.chad.library.adapter.base.BaseQuickAdapter
import com.ellecity06.common.base.BaseMvvmFragment
import com.ellecity06.common.helper.LoginHelper
import com.ellecity06.common.ktx.finishRefresh
import com.ellecity06.common.ktx.launchActivity
import com.ellecity06.common.ktx.launchActivityForResult
import com.ellecity06.common.ktx.loadByUser
import com.ellecity06.common.ktx.observeEvent
import com.ellecity06.common.ktx.statusBar
import com.ellecity06.common.ktx.stringResToString
import com.ellecity06.common.ktx.theme
import com.ellecity06.common.utils.CacheDataManager
import com.ellecity06.common.utils.CommonUtils
import com.ellecity06.common.utils.ToastUtils
import com.ellecity06.common.widgets.dialog.showAlert
import com.ellecity06.cwhiskymall.BuildConfig
import com.ellecity06.cwhiskymall.R
import com.ellecity06.cwhiskymall.adapter.ServiceMenuAdapter
import com.ellecity06.cwhiskymall.bean.MenuItem
import com.ellecity06.cwhiskymall.bean.response.StatisticalResponse
import com.ellecity06.cwhiskymall.bean.response.UserCenterResponse
import com.ellecity06.cwhiskymall.constant.BusinessConstans
import com.ellecity06.cwhiskymall.databinding.FragmentMineBinding
import com.ellecity06.cwhiskymall.storage.UserStorage
import com.ellecity06.cwhiskymall.ui.consumer_gift.ConsumerGiftActivity
import com.ellecity06.cwhiskymall.ui.contribution.ContributionActivity
import com.ellecity06.cwhiskymall.ui.login.forget.ForgetPwdActivity
import com.ellecity06.cwhiskymall.ui.login.pay.PayPwdActivity
import com.ellecity06.cwhiskymall.ui.mine.about.AboutActivity
import com.ellecity06.cwhiskymall.ui.mine.auth.AuthNameActivity
import com.ellecity06.cwhiskymall.ui.mine.auth.result.AuthInfoActivity
import com.ellecity06.cwhiskymall.ui.mine.contact.ContactUsActivity
import com.ellecity06.cwhiskymall.ui.mine.investment.InvestmentActivity
import com.ellecity06.cwhiskymall.ui.mine.newer.NewerLearningActivity
import com.ellecity06.cwhiskymall.ui.mine.test.TestActivity
import com.ellecity06.cwhiskymall.ui.service_setting.ServiceSettingActivity
import com.ellecity06.cwhiskymall.ui.user.UserInfoActivity
import com.ellecity06.cwhiskymall.ui.version.VersionUpdateActivity
import com.ellecity06.cwhiskymall.ui.webview.WebHelper
import com.ellecity06.cwhiskymall.view.dialog.ImageTipsDialog

/**
 * @author ellecity06
 * @time 2024/10/22 14:53
 * @des 我的
 */
class MineFragment : BaseMvvmFragment<FragmentMineBinding, MineViewModel>(),
    SwipeRefreshLayout.OnRefreshListener, View.OnClickListener {

    private val menuAdapter: ServiceMenuAdapter by lazy { ServiceMenuAdapter() }

    /**
     * 消费赠送提示
     */
    private val conTipsDialog: ImageTipsDialog by lazy { ImageTipsDialog(requireActivity()) }
    private val menus: MutableList<MenuItem> by lazy { mutableListOf() }


    override fun lazyInit() {
//        fetchUser()
        observeViewModel()
    }

    private fun observeViewModel() {
        viewModel.state.observeEvent(this) {
            when (it) {
                is MineState.UserCenterInfo -> {
                    binding.refreshLayout.finishRefresh()
                    setCenterInfo(it.data)
                }

                is MineState.LogoutSuccess -> {
                    LoginHelper.instance.logout(requireActivity())
                }

                is MineState.Error -> {
                    binding.refreshLayout.finishRefresh()
                }

                is MineState.UserInfo -> {
                    if (UserStorage.isHasUp()) {
                        if (UserStorage.isVip()) {
                            binding.imageVip.visibility = View.VISIBLE
                            binding.imageNotVip.visibility = View.GONE
                        } else {
                            binding.imageVip.visibility = View.GONE
                            binding.imageNotVip.visibility = View.VISIBLE
                        }
                        if (UserStorage.isHasUp()) {
                            binding.layoutAssets.visibility = View.VISIBLE
                        } else {
                            binding.layoutAssets.visibility = View.GONE
                        }
                    }

                    binding.viewLeft.visibility = UserStorage.upVisible()
                    binding.viewRight.visibility = UserStorage.upVisible()
                    handelUpUI()
                }

                is MineState.FirstOrderId -> {
//                    launchActivity<NewerGoodActivity>(Pair("categoryId", it.data))
                    WebHelper.toNewerGoosList(requireActivity(), it.data)
                }

                is MineState.GetCurrentTokenSuccess -> {
                    when (it.clickType) {
                        1 -> {
                            launchActivity<ContributionActivity>()
                        }

                        2 -> {
                            WebHelper.toAssetsSort(requireActivity())
                        }

                        3 -> {
                            WebHelper.toAssetsMarket(requireActivity())
                        }

                        4 -> {
                            WebHelper.toAssetsMine(requireActivity())
                        }
                    }

                }

                is MineState.UserStatisticalInfo -> {
                    setStatisticalInfo(it.data)
                }

                else -> {}
            }
        }
    }

    private fun setStatisticalInfo(data: StatisticalResponse?) {
        // 我的应用数量
        binding.tvAssetsAmount.text = "${data?.assetUserStatistical ?: 0}"
        // 总ip值
        binding.tvTotalAmount.text = "${data?.assetTotalMoney ?: 0.00}"
        // 零钱余额-应用值
        binding.tvPocketAmount.text = "${data?.totalBalance ?: 0.00}"


    }

    @SuppressLint("CheckResult")
    private fun setCenterInfo(data: UserCenterResponse) {
        binding.ivAvatar.loadByUser(requireActivity(), data.avatar)
        binding.tvUserName.text = data.nickName
        binding.tvId.text = "ID：${data.memberId}"
        binding.tvUserCode.text = data.inviteCode
        binding.tvPriceLevel.text = BusinessConstans.level3
        binding.tvConsumersDays.text = "已消费￥${data.alreadyAmount}第${data.whatDay}天"
        binding.tvContributionAmount.text = data.contribution
    }

    private fun fetchUser() {
        lifecycleScope.launchWhenCreated {
            viewModel.intentChannel.send(MineIntent.FetchUserInfo)
        }
    }

    private fun updateUser() {
        lifecycleScope.launchWhenCreated {
            viewModel.intentChannel.send(MineIntent.UpdateUser)
        }
    }

    override fun initView() {
        statusBar(binding.viewStatusBar)
        binding.refreshLayout.theme()
        super.initView()
        initDebug()
        initRecyclerView()
        initEvent()
    }

    private fun initDebug() {
        if (!BuildConfig.SERVER_RELEASE) {
            binding.ivSetting.setOnLongClickListener {
                launchActivity<ServiceSettingActivity>()
                true
            }
        }
    }

    private fun initEvent() {
        binding.ivAvatar.setOnClickListener(this)
        binding.tvToConvertible.setOnClickListener(this)
        binding.tvToReceive.setOnClickListener(this)
        binding.tvAddress.setOnClickListener(this)
        binding.layoutOrderPay.setOnClickListener(this)
        binding.layoutOrderSend.setOnClickListener(this)
        binding.layoutOrderReceive.setOnClickListener(this)
        binding.layoutOrderEva.setOnClickListener(this)
        binding.layoutOrderAfterSale.setOnClickListener(this)
        binding.ivCustomer.setOnClickListener(this)
        binding.ivCart.setOnClickListener(this)
        binding.ivSetting.setOnClickListener(this)
        binding.tvCopy.setOnClickListener(this)
        binding.viewOffsetHelpLeft.setOnClickListener(this)
        binding.viewOffsetHelpRight.setOnClickListener(this)
        binding.imageNotVip.setOnClickListener(this)
        binding.viewAssetsSort.setOnClickListener(this)
        binding.viewAssetsMarket.setOnClickListener(this)
        binding.tvGoWithdraw.setOnClickListener(this)
        binding.viewAssetsMine.setOnClickListener(this)
        binding.viewAssetsIp.setOnClickListener(this)
        binding.viewAssetsIpv.setOnClickListener(this)
    }

    private fun initRecyclerView() {
        binding.refreshLayout.setOnRefreshListener(this)
        binding.rvService.setHasFixedSize(true)
        binding.rvService.layoutManager = GridLayoutManager(requireActivity(), 4)
        binding.rvService.adapter = menuAdapter
        menuAdapter.setOnItemClickListener(::onServiceItemClick)
        initMenus()
        menuAdapter.submitList(menus)
    }

    private fun initMenus() {
//            MenuItem(id = 4, icon = R.mipmap.icon_service_join, name = "招商加盟"),
//            MenuItem(id = 7, icon = R.mipmap.icon_service_ticker, name = "发票助手"),
        menus.add(MenuItem(id = 10, icon = R.mipmap.icon_auth_name, name = "实名认证"))
        menus.add(MenuItem(id = 1, icon = R.mipmap.icon_service_about, name = "关于我们"))
        menus.add(MenuItem(id = 2, icon = R.mipmap.icon_service_version_check, name = "版本更新"))
        menus.add(MenuItem(id = 3, icon = R.mipmap.icon_service_find_me, name = "联系我们"))
        menus.add(MenuItem(id = 5, icon = R.mipmap.icon_service_login_psw, name = "登录密码"))
        menus.add(MenuItem(id = 6, icon = R.mipmap.icon_service_pay_psw, name = "支付密码"))
        menus.add(MenuItem(id = 8, icon = R.mipmap.icon_service_clear_cache, name = "清理缓存"))
        if (!BuildConfig.SERVER_RELEASE)
            menus.add(MenuItem(id = 1002, icon = R.mipmap.icon_mine_newer_learing, name = "测试云闪付"))
    }

    private val newerItem: MenuItem by lazy {
        MenuItem(
            id = 11,
            icon = R.mipmap.icon_mine_newer_learing,
            name = "新人教学"
        )
    }

    fun handelUpUI() {
        if (UserStorage.isHasUp()) {
            if (!menuAdapter.items.contains(newerItem)) {
                menuAdapter.add(newerItem)
            }
        } else {
            if (menuAdapter.items.contains(newerItem)) {
                menuAdapter.remove(newerItem)
            }
        }
    }

    private fun onServiceItemClick(
        baseQuickAdapter: BaseQuickAdapter<MenuItem, *>,
        view: View,
        position: Int
    ) {
        val item = menuAdapter.getItem(position)
        when (item?.id) {
            1 -> {
                // 关于我们
                launchActivity<AboutActivity>()
            }
            // 版本检查
            2 -> {
                launchActivity<VersionUpdateActivity>()
            }

            // 联系我们
            3 -> {
                launchActivity<ContactUsActivity>()
            }
            // 招商加盟
            4 -> {
                launchActivity<InvestmentActivity>()
            }
            // 登录密码
            5 -> {
                launchActivity<ForgetPwdActivity>(Pair("type", 1))
            }
            // 支付密码
            6 -> {
                launchActivity<PayPwdActivity>()
            }
            // 清理缓存
            8 -> {
                showAlert(title = "清除缓存", content = "确定清理本地缓存文件吗？") {
                    CacheDataManager.clearAllCache(requireActivity())
                }
            }

            9 -> {
                // 退出登录
                showAlert(title = "退出登录？", content = "确定退出登录吗？", onConfirm = {
                    logout()
                })
            }
            // 实名认证
            10 -> {
                if (UserStorage.user?.idCard != null && UserStorage.user?.idCard!!.isNotEmpty()) {
                    launchActivity<AuthInfoActivity>()
                } else {
                    launchActivityForResult<AuthNameActivity>(REQUEST_AUTH_CODE)
                }

            }
            // 新人教学
            11 -> {
                launchActivity<NewerLearningActivity>()
            }
            // 新人教学
            1002 -> {
                launchActivity<TestActivity>()
            }

        }
    }

    private fun logout() {
        lifecycleScope.launchWhenCreated {
            viewModel.intentChannel.send(MineIntent.Logout)
        }
    }

    override fun inflateBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentMineBinding {
        return FragmentMineBinding.inflate(inflater, container, false)
    }

    companion object {
        private const val REQUEST_EDIT_CODE = 101
        private const val REQUEST_AUTH_CODE = 102

        @JvmStatic
        fun newInstance(): MineFragment {
            return MineFragment()
        }

    }

    override fun onRefresh() {
        fetchUser()
    }

    private fun fetchIpToken(click: Boolean = false, clickType: Int = 0) {
        lifecycleScope.launchWhenCreated {
            viewModel.intentChannel.send(MineIntent.GetCurrentToken(click, clickType))
        }
    }


    override fun onClick(view: View?) {
        when (view?.id) {
            R.id.iv_avatar -> {
                launchActivityForResult<UserInfoActivity>(REQUEST_EDIT_CODE)
            }

            binding.tvToConvertible.id -> {
                // 去兑换文化应用需要先获取文化应用的token
                fetchIpToken(true, 1)

            }

            binding.tvToReceive.id -> {
                launchActivity<ConsumerGiftActivity>()
            }

            binding.tvAddress.id -> {
//                launchActivity<AddressManagerActivity>()
                WebHelper.toAddressList(requireActivity())
            }

            binding.layoutOrderPay.id -> {
                WebHelper.toOrderList(requireActivity(), 1)
            }

            binding.layoutOrderSend.id -> {
                WebHelper.toOrderList(requireActivity(), 2)
            }

            binding.layoutOrderReceive.id -> {
                WebHelper.toOrderList(requireActivity(), 3)
            }

            binding.layoutOrderAfterSale.id -> {
                WebHelper.toOrderList(requireActivity(), 4)
            }

            binding.layoutOrderEva.id -> {

            }
            // 客服
            binding.ivCustomer.id -> {
                WebHelper.toKefu(requireActivity())
            }
            // 购物车
            binding.ivCart.id -> {
                WebHelper.toShopCart(requireActivity())
            }
            // 设置
            binding.ivSetting.id -> {
                launchActivityForResult<UserInfoActivity>(REQUEST_EDIT_CODE)
            }

            binding.tvCopy.id -> {
                CommonUtils.copyStr(requireActivity(), binding.tvUserCode.text.toString())
                ToastUtils.show(R.string.text_copy_success.stringResToString())
            }

            binding.viewOffsetHelpLeft.id,
            binding.viewOffsetHelpRight.id,
            -> {
                conTipsDialog.show()
            }

            binding.imageNotVip.id -> {
                lifecycleScope.launchWhenCreated {
                    viewModel.intentChannel.send(MineIntent.FetchFirstId)
                }
            }
            /**
             * 应用排名
             */
            binding.viewAssetsSort.id -> {
                fetchIpToken(true, 2)
            }
            /**
             * 应用市场
             */
            binding.tvGoWithdraw.id,
            binding.viewAssetsMine.id,
            binding.viewAssetsIp.id,
            binding.viewAssetsIpv.id,
            -> {
                fetchIpToken(true, 4)
            }

            binding.viewAssetsMarket.id -> {
                fetchIpToken(true, 3)
            }

        }
    }

    override fun onResume() {
        super.onResume()
        updateUser()
        onRefresh()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
//        if (resultCode == Activity.RESULT_OK) {
//            onRefresh()
//        }
    }
}